<!--通过部门选择用户-->
<template>
  <BasicModal v-bind="$attrs" @register="register" :title="modalTitle" width="1200px" 
      :showCancelBtn="false" :showOkBtn="false" :canFullscreen="false" :centered="true"
      @ok="handleOk" destroyOnClose @visible-change="visibleChange"
      :bodyStyle="{height:'calc(100vh - 120px)', overflowY:'hidden'}"
    >
    <a-row :gutter="10">
      <a-col :md="7" :sm="24">
        <a-card>
          <!--组织机构-->
          <BasicTree ref="treeRef"
            :style="{ minWidth: '250px' }"
            selectable
            @select="onDepSelect"
            :load-data="loadChildrenTreeData"
            :treeData="departTree"
            :selectedKeys="selectedDepIds"
            :expandedKeys="expandedKeys"
            :clickRowToExpand="false"
          ></BasicTree>
        </a-card>
      </a-col>
      <a-col :md="17" :sm="24">
        <a-card :style="{ minHeight: '613px', overflow: 'auto' }">
          <!--用户列表-->
          <BasicTable ref="tableRef" v-bind="getBindValue" 
            :onRowClick="handleClick" 
            :onRowDbClick="handleDblclick"
            :rowClassName="rowClassName"
            :indexColumnProps="indexColumnProps" 
          ></BasicTable>
        </a-card>
      </a-col>
    </a-row>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, unref, ref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTree } from '/@/components/Tree/index';
  import { queryTreeList, getTableList } from '/@/api/common/api';
  import { list } from '/@/views/good/policy/Policy.api';
  import { columnsSel } from '/@/views/good/policy/Policy.data';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { useSelectBiz } from '/@/components/Form/src/jeecg/hooks/useSelectBiz';
  import { useAttrs } from '/@/hooks/core/useAttrs';
  import { queryDepartTreeSync } from '/@/views/system/depart/depart.api';
  import { selectProps } from '/@/components/Form/src/jeecg/props/props';
  export default defineComponent({
    name: 'UserSelectByDepModal',
    components: {
      //此处需要异步加载BasicTable
      BasicModal,
      BasicTree,
      BasicTable: createAsyncComponent(() => import('/@/components/Table/src/BasicTable.vue'), {
        loading: true,
      }),
    },
    props: {
      ...selectProps,
      //选择框标题
      modalTitle: {
        type: String,
        default: '政策产品选择',
      },
    },
    emits: ['register', 'getSelectResult'],
    setup(props, { emit, refs }) {
      const tableRef = ref();
      const treeRef = ref();
      //注册弹框
      const [register, { closeModal }] = useModalInner(async (data) => {
        await queryDepartTree();
      });
      const attrs = useAttrs();
      const departTree = ref([]);
      const selectedDepIds = ref([]);
      const expandedKeys = ref([]);
      const searchInfo = {};
      /**
       *表格配置
       */
      const tableProps = {
        columns: columnsSel,
        api: list,
        useSearchForm: true,
        canResize: true,
        showIndexColumn: true,
        clickToRowSelect: true,   //点击选择
        striped: true,
        bordered: true,
        size: 'small',
      };
      const getBindValue = Object.assign({}, unref(props), unref(attrs), tableProps);
      /**
       * 序号列配置
       */
      const indexColumnProps = {
        dataIndex: 'index',
        width: '25px',
      };
      const [{ rowSelection, visibleChange, getSelectResult, reset }] = useSelectBiz(getTableList, getBindValue);
      /**
       * 加载树形数据
       */
      function queryDepartTree() {
        queryDepartTreeSync().then((res) => {
          if (res) {
            departTree.value = res;
            // 默认展开父节点
            //expandedKeys.value = unref(departTree).map(item => item.id)
          }
        });
      }
      /**
       * 加载子级部门
       */
      async function loadChildrenTreeData(treeNode) {
        try {
          const result = await queryDepartTreeSync({
            pid: treeNode.eventKey,
          });
          const asyncTreeAction = unref(treeRef);
          if (asyncTreeAction) {
            asyncTreeAction.updateNodeByKey(treeNode.eventKey, { children: result });
            asyncTreeAction.setExpandedKeys([treeNode.eventKey, ...asyncTreeAction.getExpandedKeys()]);
          }
        } catch (e) {
          console.error(e);
        }
        return Promise.resolve();
      }
      /**
       * 点击树节点,筛选出对应的用户
       */
      function onDepSelect(keys) {
        if (keys[0] != null) {
          if (unref(selectedDepIds)[0] !== keys[0]) {
            selectedDepIds.value = [keys[0]];
          }
          searchInfo['departId'] = unref(selectedDepIds).join(',');
          tableRef.value.reload();
        }
      }
      /**
       * 自定义重置方法
       * */
      async function customResetFunc() {
        console.log('自定义查询');
        //树节点清空
        selectedDepIds.value = [];
        //查询条件清空
        searchInfo['departId'] = '';
        //选择项清空
        reset();
      }
      /**
       * 确定选择
       */
      function handleOk() {
        getSelectResult((options, values) => {
          //回传选项和已选择的值
          emit('getSelectResult', options, values);
          //关闭弹窗
          closeModal();
        });
      }

      //单击行
      let selectRows = reactive<any>({id: ''});
      function handleClick(record) {
        selectRows.id = record.id
        console.info("handleClick@@", record.id)
      }

      //选择行
      function rowClassName(record, index) {
        return record.id === selectRows.id ? 'row-selected' : '';
      }

      //双击行
      function handleDblclick(record) {
        console.info("handleDblclick@@", record)
        //handleEdit(record);
        //回传选项和已选择的值
        emit('getSelectResult', record);
        //关闭弹窗
        //closeModal();
      }

      return {
        //config,
        handleOk,
        searchInfo,
        register,
        indexColumnProps,
        visibleChange,
        getBindValue,
        rowSelection,

        departTree,
        selectedDepIds,
        expandedKeys,
        treeRef,
        tableRef,
        getTableList,
        onDepSelect,
        loadChildrenTreeData,

        handleClick,
        rowClassName,
        handleDblclick
      };
    },
  });
</script>

<style scoped lang="less"></style>
